package com.bkfm.framework.core.shiro;


import java.io.IOException;
import java.security.Principal;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.yak.core.web.Result;
import org.yak.core.web.Result.Status;

import com.alibaba.fastjson.JSONObject;
import com.bkfm.framework.core.constants.BkfmConstants;

/**
 *
 * @平台：bronca统一开发平台
 * @文件名称：ShiroFilter.java
 * @文件描述：shiro过滤器，过滤用户ajax请求回话超时
 * @author xuqiang
 * @日期：2017年4月24日下午3:59:28
 *
 */
public class ShiroFilter extends DelegatingFilterProxy {

	private static final Logger logger = Logger.getLogger(ShiroFilter.class);



	//是否ajax请求标记
	private static final String AJAX_REQUEST_FLAG="XMLHttpRequest";


	/*
	   * (non-Javadoc)
	   *
	   * @see javax.servlet.Filter#destroy()
	   */
	  @Override
	  public void destroy() {
	    

	  }

	  /*
	   * (non-Javadoc)
	   *
	   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	   */
	  @Override
	  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	      throws IOException, ServletException {


	    HttpServletRequest httpRequest = (HttpServletRequest) request;
	    HttpServletResponse httpResponse = (HttpServletResponse) response;
	    Principal principal = httpRequest.getUserPrincipal();
	    String context = httpRequest.getRequestURI().replace(httpRequest.getContextPath(), "");
	    
	    if(principal ==null || httpRequest.getSession().getAttribute(BkfmConstants.CURRENT_USER) == null)
	    {
	    	if(ShiroFilter.isAjaxRequest(httpRequest)){

	    		logger.error("Ajax请求方式，用户回话超时，系统返回登陆超时的json数据:"+httpRequest.getContextPath());
	    		httpResponse.setContentType("text/json;charset=utf-8");
	    		httpResponse.setCharacterEncoding("UTF-8");
	    		Result rs = new Result();
	    		rs.setStatus(Status.SESSION_TIMEOUT);
	    		rs.setMessage("用户回话超时，请重新登陆");
	    		httpResponse.getWriter().print(JSONObject.toJSON(rs).toString());
	    		httpResponse.getWriter().flush();
	    		httpResponse.getWriter().close();
	    	}else{
	    		logger.error("普通请求，用户登陆回话超时,页面自动跳转到登录页面");
	    		String path = httpRequest.getContextPath();
		    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
		    	httpResponse.sendRedirect(basePath+"/login");
	    	}
	    	return ;
	    }else{
	    	if(context.endsWith("/login") || context.equalsIgnoreCase("/"))
	    	{
	    		logger.info("用户已经登陆，跳转到平台主页");
		    	String path = httpRequest.getContextPath();
		    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
	    		httpResponse.sendRedirect(basePath+"/index");
	    		return ;
	    	}
	    }
	    chain.doFilter(httpRequest, httpResponse);

	  }

	  /**
	   * 判断当前请求是否为ajax请求，默认返回false
	   * @param request
	   * @return
	   * @throws Exception
	   */
	  public static boolean isAjaxRequest(HttpServletRequest request){
		  String ajaxHeader = request.getHeader("X-Requested-With");

		  //如果ajaxHeader被篡改或者不存在则可以通过使用户传入固定参数的方式来判断
		  String ajaxFlag = null == request.getParameter("ajax") ?  "false": request.getParameter("ajax") ;
		  if(AJAX_REQUEST_FLAG.equals(ajaxHeader) || ajaxFlag.equalsIgnoreCase("true")){
			  return true;
		  }

		  return false;
	  }

}